from io import BytesIO
from tempfile import NamedTemporaryFile

from flask import Blueprint, g, Response
from flask import make_response
from flask_login import login_required
from openpyxl import Workbook
from openpyxl.writer.excel import save_virtual_workbook

from apps.a_common.db import safe_commit
from apps.a_common.error import NotFound
from apps.a_common.log import MyLogger
from apps.a_common.request import assert_params_by_form
from apps.a_common.response import success_response, paginate_response, error_response, excel_response
from apps.foundation import db
from apps.users.forms import SignUpForm, UserSearchForm, UserInfoEditorForm
from apps.users.helper import create_user, get_permissions_by_user_id, set_user_info_by_form, search_user_by_form, \
    generate_user_excel
from apps.users.models import User
from apps.users.serializers import serialize_user, serialize_user_all_info

user_manage_blueprint = Blueprint('user_manage', __name__)
log = MyLogger('user manage view')


@user_manage_blueprint.route('/user-manage/', methods=['GET'])
@login_required
def _manage_user_info():
    """
    用户的列表
    ---
    tags:
      - user-manage
    parameters:
      - name: skills
        in : query
        type: integer
        required: false
        description: 根据技能查User，如果需要查询一个人同时拥有技能1和技能2，需要这样查询/v1/api/user-manage/?skills=1&skills=2
      - name: project_id
        in : query
        type: integer
        required: false
        description: 项目的id
      - name: page_id
        in : query
        type: integer
        required: false
        default: 1
        description: 页码
      - name: page_size
        in : query
        type: integer
        required: false
        default: 20
        description: 每页的大小
    """
    form = assert_params_by_form(UserSearchForm)
    log.info(form)
    queryset = search_user_by_form(form)
    return paginate_response(queryset, serialize_user_all_info)


@user_manage_blueprint.route('/users-manage/', methods=['POST'])
def _manage_create_user():
    """
    创建用户
    ---
    tags:
      - user-manage
    parameters:
      - name: username
        in : formData
        type: string
        required: true
        description: 用户昵称
      - name: password
        in : formData
        type: string
        required: true
        description: 用户密码
      - name: confirm_password
        in : formData
        type: string
        required: true
        description: 用户密码
    """
    form = assert_params_by_form(SignUpForm)
    user = create_user(form)
    permissions = get_permissions_by_user_id(user.id)
    return success_response(serialize_user(user, permissions))


@user_manage_blueprint.route('/users-manage/<int:user_id>/', methods=['PUT'])
@login_required
def _manage_put_user_info(user_id):
    """
    修改用户信息
    ---
    tags:
      - user-manage
    parameters:
      - name: user_id
        in : path
        type: integer
        required: true
        description: 用户的id
      - name: password
        in : formData
        type: string
        required: false
        description: 用户密码
      - name: nickname
        in : formData
        type: string
        required: false
        description: 用户昵称
      - name: avatar
        in : formData
        type: string
        required: false
        description: 用户头像的url，用户的头像先通过file接口上传，再将url传给后端
      - name: skills
        in : formData
        type: array
        required: false
        description: 员工的技能
      - name: first_name
        in : formData
        type: string
        required: false
        description: 员工的名字的姓
      - name: last_name
        in : formData
        type: string
        required: false
        description: 员工的名字的名
      - name: sex
        in : formData
        type: integer
        required: false
        description: 员工的性别，1为男，2为女
      - name: work_experience
        in : formData
        type: string
        required: false
        description: 员工的性别，1为男，2为女
    """
    form = assert_params_by_form(UserInfoEditorForm)
    user = User.query.filter(User.id == user_id).first()
    user = set_user_info_by_form(user, form)
    permissions = get_permissions_by_user_id(user.id)
    safe_commit()
    return success_response(serialize_user_all_info(g.user, permissions))


@user_manage_blueprint.route('/users-manage/<int:user_id>/', methods=['DELETE'])
@login_required
def _manage_delete_user_info(user_id):
    """
    删除用户
    ---
    tags:
      - user-manage
    parameters:
      - name: user_id
        in : path
        type: integer
        required: true
        description: 用户的id
    """
    user = User.query.filter(User.id == user_id).first()
    if not user:
        return error_response(NotFound())
    db.session.delete(user)
    safe_commit()
    return success_response(serialize_user_all_info(g.user))


@user_manage_blueprint.route('/users-manage/download/', methods=['GET'])
@login_required
def _manage_download_user_info():
    """
    下载User信息，因为这个API工具有bug，建议直接在游览其中打开 ***/v1/api/users-manage/download/
    ---
    tags:
      - user-manage
    parameters:
      - name: skills
        in : query
        type: integer
        required: false
        description: 根据技能查User，如果需要查询一个人同时拥有技能1和技能2，需要这样查询/v1/api/user-manage/?skills=1&skills=2
      - name: project_id
        in : query
        type: integer
        required: false
        description: 项目的id
    """
    form = assert_params_by_form(UserSearchForm)
    queryset = search_user_by_form(form)

    wb = generate_user_excel(queryset.all())
    return excel_response(wb, 'user_list.xlsx')
